package com.shop.servlet.config;

import com.api.openfeign.client.UserClient;
import com.api.openfeign.dto.UserDto;

import com.shop.servlet.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;


@Configuration
public class CommonSecurityConfig {

@Autowired
private UserClient userClient;
    @Bean
    public UserDetailsService userDetailsService() {

        return username -> {
            UserDto userDto;
            try {
                userDto = userClient.username(username);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            if (userDto == null) {
                throw new UsernameNotFoundException("用户不存在");
            }
            // 关键：必须设置正确的权限（即使是默认权限），否则认证后可能因权限不足返回403
           // List<GrantedAuthority> authorities = new ArrayList<>();
            //authorities.add(new SimpleGrantedAuthority("ROLE_USER")); // 添加默认角色

            return new LoginUser(
                    userDto.getId(),
                    username,
                    userDto.getEmail(),
                    userDto.getPassword()
            );
        };
    }

}
